package look4ss.aplicativo;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import im.delight.android.location.SimpleLocation;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import look4ss.aplicativo.lista.Pontos;
import look4ss.aplicativo.fragments.AbaMapa;

public class Intro extends AppCompatActivity {

    private TextView iniciar;
    public static String nome, descricao, imagem, datahora;
    public static Pontos pontos;
    public static ArrayList<Pontos> listaitens = new ArrayList<Pontos>();
    private ProgressBar Carregando;
    public SimpleLocation localizacao;
    public SharedPreferences sharp;
    public SharedPreferences.Editor sharp_edt;
    private TextView textoPular;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intro_loading);
        Carregando = this.findViewById(R.id.barraCarregamento);
        localizacao = new SimpleLocation(Intro.this, false, false, 600000, false);
        localizacao.beginUpdates();
        textoPular = this.findViewById(R.id.iniciar);
        new classe().execute();
        getWindow().setFormat(PixelFormat.UNKNOWN);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        iniciar = findViewById(R.id.iniciar);
        localizarCidade();
        iniciar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    private void localizarCidade() {
        localizacao.beginUpdates();
        try {
            Double latitude = localizacao.getLatitude();
            Double longitude = localizacao.getLongitude();

            if (latitude != 0.0) {
                AbaMapa.latitudeSalva = latitude.toString();
                AbaMapa.longitudeSalva = longitude.toString();
                sharp = getSharedPreferences("cidade", Context.MODE_PRIVATE);
                SharedPreferences.Editor edtr = sharp.edit();
                edtr.putString("latitude", latitude.toString());
                edtr.putString("longitude", longitude.toString());
                edtr.apply();
            }
            if (latitude == 0.0 || latitude == null || latitude.toString().isEmpty()) {
                sharp = getSharedPreferences("cidade", Context.MODE_PRIVATE);
                AbaMapa.latitudeSalva = sharp.getString("latitude", "0.0");
                AbaMapa.longitudeSalva = sharp.getString("longitude", "0.0");
            }
            if(AbaMapa.latitudeSalva.equals("0.0") && AbaMapa.longitudeSalva.equals("0.0")) {
                startActivity(new Intent(Intro.this, Aviso.class));
                finish();
            }
        }catch (Exception ex) {

        }
    }


    class classe extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Carregando.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(variaveisGlobais.urlDados).build();

            try {
                Response response = client.newCall(request).execute();
                String data = response.body().string();

                if (!response.isSuccessful()) {
                    throw new IOException("Erro " + response);
                }
                return data;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Carregando.setVisibility(View.GONE);
            textoPular.setVisibility(View.VISIBLE);
            try {
                JSONObject objectp = new JSONObject(s);
                JSONArray jArrPoints = objectp.getJSONArray("pontos");

                for (int i = 0; i < jArrPoints.length(); i++) {
                    pontos = new Pontos();
                    pontos.defineNome(jArrPoints.getJSONObject(i).getString("titulo"));
                    pontos.defineLatitude(jArrPoints.getJSONObject(i).getString("latitude"));
                    pontos.defineLongitude(jArrPoints.getJSONObject(i).getString("longitude"));
                    pontos.defineImagem(jArrPoints.getJSONObject(i).getString("imagem"));
                    pontos.defineIdUsuario(jArrPoints.getJSONObject(i).getString("idUsuario"));
                    pontos.defineCodigoEnvio(jArrPoints.getJSONObject(i).getString("idEnvio"));
                    pontos.defineNomePessoa(jArrPoints.getJSONObject(i).getString("nome_pessoa"));
                    pontos.defineDataHora(jArrPoints.getJSONObject(i).getString("tempo"));
                    listaitens.add(pontos);
                }
                AbaMapa.listaitens = listaitens;

            } catch (JSONException e) {
                e.printStackTrace();
            }

            CountDownTimer contadorTempo = new CountDownTimer(800, 400) {
                public void onTick(long x) {
                }

                public void onFinish() {
                    localizacao.endUpdates();
                    textoPular.performClick();
                    this.start();
                }
            }.start();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        localizacao.beginUpdates();
    }
    @Override
    public void onPause() {
        localizacao.endUpdates();
        super.onPause();
    }
    @Override
    public void onStop() {
        localizacao.endUpdates();
        super.onStop();
    }
    @Override
    public void onDestroy() {
        localizacao.endUpdates();
        super.onDestroy();
    }

}